import { login, logout } from '@/api/login'
import { getInfo } from '@/api/system/account'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token)
            commit('SET_TOKEN', res.token)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const { permissions, role, name } = res

            // 前端自定义全局路由权限标识
            const _permissions = permissions.filter(e => e.permission_alias).map(e => e.permission_alias)
            // const _permissions = ['*:*:*']

            console.log('登录账号的permissions===', permissions)
            console.log('登录账号的_permissions===', _permissions)

            const avatar =
              res.avatar == '' || res.avatar == null
                ? require('@/assets/images/profile.jpg')
                : process.env.VUE_APP_BASE_API + res.avatar
            if (role) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', [role])
              commit('SET_PERMISSIONS', _permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_NAME', name)
            commit('SET_AVATAR', avatar)

            successRouter(permissions, true).then((userLeftMenuRouter) => {
              successRouter(permissions, false).then((userHaveRouter) => {
                resolve({
                  userHaveRouter,
                  userLeftMenuRouter
                })
              })
            })
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resolve()
      //   logout(state.token)
      //     .then(() => {
      //       commit('SET_TOKEN', '')
      //       commit('SET_ROLES', [])
      //       commit('SET_PERMISSIONS', [])
      //       removeToken()
      //       resolve()
      //     })
      //     .catch((error) => {
      //       reject(error)
      //     })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

/** 模拟对标routerData.js数据
 * isLeftMenu: true左侧菜单显示的路由
 * isLeftMenu: false所有登录用户可以访问的路由
 * */
function successRouter(array, isLeftMenu = false) {
  return new Promise(resolve => {
    const result = []
    let pageRoute = []
    if (isLeftMenu) {
      // 筛选出【菜单】的数据
      pageRoute = array.filter(e => e.type === 1)
    } else {
      // 筛选出【菜单】【普通页面】的数据
      pageRoute = array.filter(e => e.type === 1 || e.type === 3)
    }

    const deepRouteArray = JSON.parse(JSON.stringify(pageRoute))

    const fatherArr = deepRouteArray.filter(e => e.parent_id === 0)
    deepRouteArray.forEach(e => {
      const { parent_id, name, path, view, icon, type, sort } = e

      if (parent_id === 0) {
        const fatherItem = {
          name: path,
          path: `/${view}`,
          hidden: false,
          redirect: 'noRedirect',
          component: 'Layout',
          alwaysShow: true,
          meta: { title: name, icon, noCache: false, link: null, pageType: type, sort },
          children: []
        }
        result.push(JSON.parse(JSON.stringify(fatherItem)))
      } else {
        /**
         * 接口参数返回
         * path: VideoedList（对应router配置的name属性）
         * view: 组件文件目录（对应router配置的component属性）
         * */
        const fatherIndex = fatherArr.findIndex(father => father.id === parent_id)
        if (fatherIndex === -1) return

        const thisResult = result[fatherIndex]
        // 把父页面的路径删掉，得到当前页面的正确路径，如statistics/videoed/list =>  videoed/list
        const _path = view.split('/').filter((e, index) => index > 0).join('/')
        // 子级
        const childrenItem = {
          name: path,
          path: _path,
          hidden: false,
          component: view,
          meta: { title: name, icon: icon, noCache: false, link: null, pageType: type, sort }
        }
        if (thisResult && thisResult.children) {
          thisResult.children.push(childrenItem)
          thisResult.children.sort((a, b) => a.meta.sort - b.meta.sort)
        } else {
          console.log(result, fatherIndex)
          console.error('尚未找到一级路由')
        }
      }
    })
    result.sort((a, b) => {
      return a.meta.sort - b.meta.sort
    })
    console.log('最终得到路由配置文件======当前账号拥有的路由', result)
    resolve(result)
  })
}

export default user
